//
//  DRCookViewController.m
//  DoctorRen
//
//  Created by Lemon on 2018/11/19.
//

#import "DRCookViewController.h"
#import "DRLearnCookingModel.h"
#import "DRCookSociaModel.h"
#import "DRCookDataModel.h"
#import "DRLearnCookCell.h"
#import "DRCookSocialCell.h"
#import <YBImageBrowser/YBImageBrowser.h>
#import "DRSocialLikeCell.h"
#import "DRSocialCommentCell.h"
#import "UUKeyboardInputView.h"

@interface DRCookViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segment;

@property (nonatomic, strong) DRHttpModel *f_httpModel;//煮友圈
@property (nonatomic, strong) DRHttpModel *l_httpModel;//学煮艺

@property (nonatomic, strong) DRHttpModel *update_l_httpModel;

@property (nonatomic, strong) NSMutableArray <DRLearnCookingModel *> *l_cellModels;
@property (nonatomic, strong) NSMutableArray <DRCookSociaModel *> *f_cellModels;
@property (weak, nonatomic) IBOutlet UIButton *publishBtn;

@property (nonatomic, assign) BOOL isPopToWebVC;

@end

@implementation DRCookViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 348;
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    layout.itemSize = CGSizeMake(SCREEN_WIDTH / 2 - 20, 276);
    layout.sectionInset= UIEdgeInsetsMake(0, 15, 0, 15);
    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        STRONGSELF
        [strongSelf tableViewHeaderRefresh];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        STRONGSELF
        [strongSelf tableViewFooderRefresh];
    }];
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        STRONGSELF
        [strongSelf collectionViewHeaderRefresh];
    }];
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        STRONGSELF
        NSLog(@"=======mj_footer========");
        [strongSelf collectionViewFooderRefresh];
    }];
    [self tableViewHeaderRefresh];
    [self collectionViewHeaderRefresh];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadToken) name:kLoginSuccess object:nil];
    
    if(@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.tableView.translatesAutoresizingMaskIntoConstraints = NO;
        self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
    }
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self setKefuButtonHidden:NO];
//    [self updateLearnCookData:1];
    if (self.isPopToWebVC) {
        [self collectionViewHeaderRefresh];
        self.isPopToWebVC = NO;
    }
    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}

-(void) reloadToken{
    self.f_httpModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
    self.l_httpModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
    [self tableViewHeaderRefresh];
    [self collectionViewHeaderRefresh];
}


- (IBAction)clickSegment:(UISegmentedControl *)sender {
    BOOL showFinish = sender.selectedSegmentIndex == 0;
    [self.collectionView setHidden:!showFinish];
    [self.tableView setHidden:showFinish];
    [self.publishBtn setImage:[UIImage imageNamed:showFinish ? @"我晒煮艺" : @"我要发布"] forState:(UIControlStateNormal)];
}
- (IBAction)clickPublishButton:(id)sender {
    if ([DRLoginDataModel getUserToken].length == 0) {
        [self presentNeedLogin:NO];
        return;
    }
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    if (self.segment.selectedSegmentIndex == 0) {
        [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/baskCooking?token=%@&isBack=1",[DRLoginDataModel getUserToken]]];
    }else {
        //http://rsjkkj.com/dist/#/issue
        [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/issue?token=%@&isBack=1",[DRLoginDataModel getUserToken]]];
    }

}

-(void) loadCookSociaData:(BOOL) isPull{
    WEAKSELF
    [DRCookDataModel loadFriendCircleData:self.f_httpModel andSuccess:^(NSArray<DRCookSociaModel *> * _Nonnull models) {
        STRONGSELF
        if (isPull) {
            [weakSelf.f_cellModels removeAllObjects];
        }
        for (DRCookSociaModel *m in strongSelf.f_cellModels) {
            for (DRCookSociaModel * n in models) {
                if ([m._id isEqualToString:n._id] && [m.content isEqualToString:n.content] && [m.create_time isEqualToString:n.create_time] && [m.user_pic_id isEqualToString:n.user_pic_id]) {
                    return ;
                }
            }
        }
        [weakSelf.f_cellModels addObjectsFromArray:models];

        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_header endRefreshing];
            if (models.count == 0) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
                [weakSelf.tableView reloadData];
            }
        });
        
    } andFail:^(NSError *error) {
        if (error.code == 500) {
            [SVProgressHUD dismiss];
            
            if (![DRLoginDataModel isLogin]) {
                return ;
            }
            [DRLoginDataModel setIsLogin:NO];
            [weakSelf presentAlertViewWithTitle:@"请重新登录" message:@"" confirmTitle:@"确定" handler:^{
                [weakSelf gotoLogin];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            
        }
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

-(void) loadLearnCookData:(BOOL) isPull{
    NSLog(@"===============");
    WEAKSELF
    [DRCookDataModel loadLearnCookingData:self.l_httpModel andSuccess:^(NSArray<DRLearnCookingModel *> * _Nonnull models) {
        STRONGSELF
        [SVProgressHUD dismiss];

        if (isPull) {
            [strongSelf.l_cellModels removeAllObjects];
        }
        //后续寻找bug
        for (DRLearnCookingModel *m in strongSelf.l_cellModels) {
            for (DRLearnCookingModel * n in models) {
                if ([m._id isEqualToString:n._id] && [m.user_id isEqualToString:n.user_id] && [m.title isEqualToString:n.title]) {
                    return ;
                }
            }
        }
        
        [strongSelf.l_cellModels addObjectsFromArray:models];
        dispatch_async(dispatch_get_main_queue(), ^{
            [strongSelf.collectionView.mj_header endRefreshing];
            [strongSelf.collectionView.mj_footer endRefreshing];
            if (models.count == 0) {
                [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [strongSelf.collectionView reloadData];
            }
        });

        
    } andFail:^(NSError *error) {
        if (error.code == 500) {
            [SVProgressHUD dismiss];
            WEAKSELF
            if (![DRLoginDataModel isLogin]) {
                return ;
            }
            [DRLoginDataModel setIsLogin:NO];
            [weakSelf presentAlertViewWithTitle:@"请重新登录" message:@"" confirmTitle:@"确定" handler:^{
                [weakSelf gotoLogin];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            
        }
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
}

-(void) collectionViewHeaderRefresh{
    self.l_httpModel.pageIndex = 1;
    [self.collectionView.mj_footer resetNoMoreData];
    [self loadLearnCookData:YES];
}

-(void) collectionViewFooderRefresh{
    self.l_httpModel.pageIndex += 1;
    [self loadLearnCookData:NO];
}

-(void) tableViewHeaderRefresh{
    self.f_httpModel.pageIndex = 1;
//    [self.f_cellModels removeAllObjects];
    [self.tableView.mj_footer resetNoMoreData];
    [self loadCookSociaData:YES];
}

-(void) tableViewFooderRefresh{
    self.f_httpModel.pageIndex += 1;
    [self loadCookSociaData:NO];
}

-(DRHttpModel *)f_httpModel{
    if (!_f_httpModel) {
        _f_httpModel = [DRHttpModel new];
        _f_httpModel.url = DRURL(@"index.php/Apicookingart/zylist");
        _f_httpModel.pageIndex = 1;
        _f_httpModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
        _f_httpModel.type = DRGet;
    }
    return _f_httpModel;
}

-(DRHttpModel *)l_httpModel{
    if (!_l_httpModel) {
        _l_httpModel = [DRHttpModel new];
        _l_httpModel.url = DRURL(@"index.php/Apicookingart/healthylist") ;
        _l_httpModel.pageIndex = 1;
        _l_httpModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
        _l_httpModel.type = DRGet;
    }
    return _l_httpModel;
}

-(DRHttpModel *)update_l_httpModel{
    if (!_update_l_httpModel) {
        _update_l_httpModel = [DRHttpModel new];
        _update_l_httpModel.url = DRURL(@"index.php/Apicookingart/healthylist") ;
        _update_l_httpModel.pageIndex = 1;
        _update_l_httpModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
        _update_l_httpModel.type = DRGet;
    }
    return _update_l_httpModel;
}

-(NSMutableArray<DRCookSociaModel *> *)f_cellModels{
    if (!_f_cellModels) {
        _f_cellModels = [NSMutableArray array];
    }
    return _f_cellModels;
}

-(NSMutableArray<DRLearnCookingModel *> *)l_cellModels{
    if (!_l_cellModels) {
        _l_cellModels = [NSMutableArray array];
    }
    return _l_cellModels;
}

#pragma UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.f_cellModels.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    DRCookSociaModel *model = self.f_cellModels[section];
    NSInteger count = 1;
    if (model.goodarr.count > 0) {
        count += 1;
    }
    if (model.commentsarr.count > 0) {
        count += model.commentsarr.count;
    }
    return count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DRCookSociaModel *model = self.f_cellModels[indexPath.section];
    BOOL hasLike = model.goodarr.count > 0;
    UITableViewCell *_cell = nil;
    if (indexPath.row == 0) {
        DRCookSocialCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRCookSocialCell" forIndexPath:indexPath];
        _cell = cell;
        [cell setData:model];
        //点击图片
        cell.tapAction = ^(NSArray *urlArray, NSInteger currentIndex) {
            NSMutableArray *array = [NSMutableArray arrayWithCapacity:urlArray.count];
            for (NSString *url in urlArray) {
                if ([@[@"mov",@"mp4",@"avi"] containsObject:url.pathExtension.lowercaseString]){
                    //视频
                    YBVideoBrowseCellData *data = [YBVideoBrowseCellData new];
                    data.url = [NSURL URLWithString:url];
                    [array addObject:data];
                }else{
                    //图片
                    YBImageBrowseCellData *data = [YBImageBrowseCellData new];
                    data.url = [NSURL URLWithString:url];
                    //            data.sourceObject = cell;
                    [array addObject:data];
                }
                
            }
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = array;
            browser.currentIndex = currentIndex;
            UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
            [button setImage:[UIImage imageNamed:@"操作栏_返回_白色"] forState:(UIControlStateNormal)];
            button.frame = CGRectMake(0, 10, 20, 30);
            [browser show];
            [browser.defaultToolBar addSubview:button];
            [button addTarget:self action:@selector(hideBrowser:) forControlEvents:(UIControlEventTouchUpInside)];
;
            
        };
        //点赞
        WEAKSELF
        cell.likeAction = ^{
            [weakSelf likeAction:model];
        };
        
        //评论
        cell.commentAction = ^{
            NSLog(@"id :%@",model._id);
            [weakSelf addComment:model];
        };
        
    }else if (hasLike && indexPath.row == 1){
        DRSocialLikeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRSocialLikeCell"];
        if (!cell) {
            cell = [[DRSocialLikeCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"DRSocialLikeCell"];
        }
        [cell setGoods:model.goodarr];
        _cell = cell;
    }else{
        DRSocialCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRSocialCommentCell"];
        if (!cell) {
            cell = [[DRSocialCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DRSocialCommentCell"];
        }
        NSInteger index = indexPath.row - 1 - (hasLike ? 1: 0);
        [cell setComment:model.commentsarr[index] isFirst:(index == 0)];
        _cell = cell;
    }
    
    return _cell;
}

-(void) hideBrowser:(UIButton *) button{
    for (UIView* next = [button superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[YBImageBrowser class]]) {
            YBImageBrowser *browser = (YBImageBrowser*)nextResponder;
            [browser hide];
        }
    }
    

}

-(void) addComment:(DRCookSociaModel *) model{
    [UUKeyboardInputView showKeyboardConfige:^(UUInputConfiger * _Nonnull configer) {
        // 配置信息（后续可继续添加）
        configer.keyboardType = UIKeyboardTypeDefault;
//        configer.content = content;
        configer.backgroundColor = [UIColor clearColor];
        
    } block:^(NSString * _Nonnull contentStr) {
        // 回调事件处理
        NSLog(@"%@",contentStr);
        if ([NSString isNullOrEmpty:contentStr]) return ;
        [DRCookDataModel comment:model._id content:contentStr andSuccess:^{
            NSMutableArray *array = [NSMutableArray arrayWithArray:model.commentsarr];
            DRUserModel *user = [DRLoginDataModel getUserModel];
            [array addObject:@{
                               @"id": @"-1111",
                               @"content": contentStr,
                               @"user_name": user.name
                               }];
            model.commentsarr = [array copy];
            [self.tableView reloadData];
        } andFail:^(NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        }];
    }];
}
//煮友圈点赞
-(void) likeAction:(DRCookSociaModel *) m{
    
    [DRCookDataModel giveLike:m._id andSuccess:^(NSInteger code) {
        //因为后台请求没有做pageSize的控制，要不就重新请求，会导致tableView数据不一样
        m.hascollection = code == 0;
        DRUserModel *model = [DRLoginDataModel getUserModel];
        if (code == 0) {
            //添加
            NSMutableArray *arr = [NSMutableArray arrayWithArray:m.goodarr];
            [arr addObject:@{@"user_id":model.name ,@"id":@"-1111"}];
            m.good = [@([m.good integerValue] + 1) stringValue];
            m.goodarr = arr;
        }else{
            //减去
            NSMutableArray *arr = [NSMutableArray arrayWithArray:m.goodarr];
            for (NSDictionary *dic in arr) {
                if ([dic[@"user_id"] isEqualToString:model.name]) {
                    [arr removeObject:dic];
                    break;
                }
            }
            m.good = [@([m.good integerValue] - 1) stringValue];
            m.goodarr = arr;
        }
        [self.tableView reloadData];
        
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

-(void) likeAction2:(DRLearnCookingModel *) model{
    [DRCookDataModel giveLikeHealthy:model._id isLike:model.is_like andSuccess:^{
        NSInteger count = [model.like_count integerValue];
        count = model.is_like ? count - 1 : count + 1;
        model.is_like = !model.is_like;
        model.like_count = [NSString stringWithFormat:@"%ld", count];
        [self.collectionView reloadData];
        [SVProgressHUD showSuccessWithStatus:model.is_like ? @"点赞成功" : @"取消点赞"];
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

#pragma UICollectionView

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.l_cellModels.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DRLearnCookCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DRLearnCookCell" forIndexPath:indexPath];
    DRLearnCookingModel *model = self.l_cellModels[indexPath.row];
    [cell setData:model];
    WEAKSELF
    cell.likeComment = ^{
        STRONGSELF
        [strongSelf likeAction2:model];
    };
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController setNavigationBarHidden:YES animated:NO];
        [self pushWebViewWithUrl:self.l_cellModels[indexPath.row].url];
        self.isPopToWebVC = true;
    });

}

@end
